package com.wanli.agent.homepage;


import android.app.Dialog;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.wanli.agent.R;
import com.wanli.agent.base.BaseFragment;
import com.wanli.agent.base.DataCallBack;
import com.wanli.agent.bean.IncomeListBean;
import com.wanli.agent.bean.OrderFeeBean;
import com.wanli.agent.homepage.adapter.ReturnIncomeListAdapter;
import com.wanli.agent.homepage.model.HomePageModelImpl;
import com.wanli.agent.homepage.model.IHomePageModel;
import com.wanli.agent.utils.DateTimeUtil;
import com.wanli.agent.utils.NumberFormatUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 返现收益
 */
public class IncomeReturnFragment extends BaseFragment implements OnRefreshLoadMoreListener {

    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.ll_start_time)
    LinearLayout llStartTime;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R.id.ll_end_time)
    LinearLayout llEndTime;
    @BindView(R.id.ll_no_data)
    LinearLayout llNoData;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.tv_list_money)
    TextView tvListMoney;
    @BindView(R.id.tv_today_money)
    TextView tvTodayMoney;
    @BindView(R.id.tv_yesterday_money)
    TextView tvYesterdayMoney;
    @BindView(R.id.tv_current_month)
    TextView tvCurrentMonth;
    private IHomePageModel homePageModel;
    private String start_time;
    private String end_time;
    private int timeType = 1;
    private Calendar selectedDate;

    private List<IncomeListBean.DataBean.ItemListBean> beanList;
    private ReturnIncomeListAdapter listAdapter;
    private int page = 1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_return_income, container, false);
        ButterKnife.bind(this, view);
        initView();
        initData();
        return view;
    }

    private void initView() {
        refreshLayout.setRefreshHeader(new ClassicsHeader(mActivity));//设置Header
        refreshLayout.setRefreshFooter(new ClassicsFooter(mActivity));//设置Footer
        refreshLayout.setOnRefreshLoadMoreListener(this);
    }


    public void initData() {
        homePageModel = new HomePageModelImpl();
        start_time = DateTimeUtil.format(new Date());
        end_time = DateTimeUtil.format(new Date());
        selectedDate = Calendar.getInstance();

        tvStartTime.setText(start_time);
        tvEndTime.setText(end_time);

        beanList = new ArrayList<>();
        listAdapter = new ReturnIncomeListAdapter(beanList);
        recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        recyclerView.setAdapter(listAdapter);
        requestReturnfliterSum();
        requestReturncashOrderDetailList();
    }


    private TimePickerView pvTime;

    public void selectTime() {
        //这里可以更改参数，有好多类型
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();
        startDate.set(1900, 0, 1);
        endDate.set(2099, 11, 31);
        pvTime = new TimePickerBuilder(mActivity, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                if (timeType == 1) {
                    start_time = DateTimeUtil.format(date);
                    tvStartTime.setText(start_time);
                } else {
                    end_time = DateTimeUtil.format(date);
                    tvEndTime.setText(end_time);
                }
                refreshData();
            }
        }).setType(new boolean[]{true, true, true, false, false, false})
                .setSubmitColor(getResources().getColor(R.color.text_color_2))//确定按钮文字颜色
                .setSubCalSize(14)
                .setCancelColor(getResources().getColor(R.color.text_color_2))//取消按钮文字颜色
                .setTitleBgColor(getResources().getColor(R.color.white))
                .setDividerColor(getResources().getColor(R.color.line_color_gray))
                .setTextColorCenter(getResources().getColor(R.color.text_color_2))
                .setContentTextSize(15)
                .setLineSpacingMultiplier(2)
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window window = mDialog.getWindow();
            if (window != null) {
                window.setWindowAnimations(R.style.picker_view_slide_anim);//修改动画样式
                window.getDecorView().setPadding(0, 0, 0, 0);
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
                lp.gravity = Gravity.BOTTOM;
            }
        }
        pvTime.show();
    }

    public void requestReturnfliterSum() {
        homePageModel.requestReturnfliterSum(new DataCallBack<OrderFeeBean>() {
            @Override
            public void onSuccessful(OrderFeeBean bean) {
                String total = NumberFormatUtils.formatTwoDecimal(bean.getData().getTotal() / 100);
                tvListMoney.setText(total);
                String today = NumberFormatUtils.formatTwoDecimal(bean.getData().getToday() / 100);
                tvTodayMoney.setText(today);
                String yesterday = NumberFormatUtils.formatTwoDecimal(bean.getData().getYesterday() / 100);
                tvYesterdayMoney.setText(yesterday);
                String month = NumberFormatUtils.formatTwoDecimal(bean.getData().getMonth() / 100);
                tvCurrentMonth.setText(month);
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    public void requestReturncashOrderDetailList() {
        homePageModel.requestReturncashOrderDetailList(page, start_time, end_time, new DataCallBack<IncomeListBean>() {
            @Override
            public void onSuccessful(IncomeListBean bean) {
                if (bean.getData().getItemList() != null && bean.getData().getItemList().size() > 0) {
                    beanList.addAll(bean.getData().getItemList());
                    if (page == 1) {
                        refreshLayout.finishRefresh();
                    } else {
                        refreshLayout.finishLoadMore();
                    }
                } else {
                    if (page != 1) {
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    } else {
                        refreshLayout.finishRefresh();
                    }
                }
                if (beanList.size() > 0) {
                    llNoData.setVisibility(View.GONE);
                } else {
                    llNoData.setVisibility(View.VISIBLE);
                }
                listAdapter.notifyDataSetChanged();

//                String money = NumberFormatUtils.formatTwoDecimal(bean.getData().getTotal().getShare_money_count() / 100);
//                tvListMoney.setText(money);
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        page++;
        requestReturncashOrderDetailList();
        refreshLayout.finishLoadMore(30000);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        refreshData();
    }

    public void refreshData() {
        page = 1;
        beanList.clear();
        requestReturncashOrderDetailList();
        refreshLayout.finishRefresh(30000);
    }

    @OnClick({R.id.ll_start_time, R.id.ll_end_time})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_start_time:
                selectedDate.setTime(DateTimeUtil.parse(tvStartTime.getText().toString()));
                timeType = 1;
                selectTime();
                break;
            case R.id.ll_end_time:
                selectedDate.setTime(DateTimeUtil.parse(tvEndTime.getText().toString()));
                timeType = 2;
                selectTime();
                break;
        }
    }
}
